package com.wzt.lianfirecontrol.fragment.xuncha;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.xuncha.XunChaQuestionAdapter;
import com.wzt.lianfirecontrol.adapter.xuncha.XunChaSelectBuildAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaBuildingModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaFloorModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaPlanModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaQuestionModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;

import java.util.HashMap;
import java.util.LinkedList;

public class XunChaCompleteFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_info_list;
    private XunChaSelectBuildAdapter xunChaSelectBuildAdapter;
    private LinearLayoutManager llm_info_list;
    private LinearLayout ll_que_title;

    private RecyclerView rlv_question_list;
    private XunChaQuestionAdapter xunChaQuestionAdapter;
    private LinearLayoutManager llm_question;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int INFO_LIST_REQUEST_WHAT = 0;
    private static final int QUS_LIST_WHAT = 1;

    private XunChaPlanModel xunChaPlanModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            bundle = getArguments();
            if (bundle != null){
                xunChaPlanModel = (XunChaPlanModel) bundle.getSerializable("data");
            }
            if (null == xunChaPlanModel){
                activity.finish();
            }
            itemContentView = inflater.inflate(R.layout.f_xuncha_complete, container, false);
            initView();
            initHttpHelper();
            initQusHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {

        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));

        initQuestionListView();

        initBuildListView();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initBuildListView() {
        View headView = LayoutInflater.from(activity).inflate(R.layout.head_xuncha_complete, rlv_question_list, false);
        xunChaQuestionAdapter.setHeaderView(headView);

        rlv_info_list = headView.findViewById(R.id.rlv_info_list);
        llm_info_list = new LinearLayoutManager(activity);
        llm_info_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_info_list.setLayoutManager(llm_info_list);

        xunChaSelectBuildAdapter = new XunChaSelectBuildAdapter(activity);
        xunChaSelectBuildAdapter.setComplete(true);
        rlv_info_list.setAdapter(xunChaSelectBuildAdapter);

        ll_que_title = headView.findViewById(R.id.ll_que_title);
    }

    private void initQuestionListView() {
        rlv_question_list = itemContentView.findViewById(R.id.rlv_question_list);
        llm_question = new LinearLayoutManager(activity);
        llm_question.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_question_list.setLayoutManager(llm_question);

        xunChaQuestionAdapter = new XunChaQuestionAdapter(activity);
        xunChaQuestionAdapter.setComplete(true);
        rlv_question_list.setAdapter(xunChaQuestionAdapter);

        xunChaQuestionAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<XunChaQuestionModel>() {
            @Override
            public void onItemClick(View v, int position, XunChaQuestionModel data) {
                // 防火巡检查问题列表点击动作
                Bundle skipToBundle = new Bundle();
                skipToBundle.putSerializable("data", data);
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.XUNCHADETAIL);
                bannerModel.setActionTitle( "问题详情");
                activity.setClickAction(bannerModel, skipToBundle);
            }
        });
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
        initQusHttpHelper();
    }



    /**
     * 获取列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", xunChaPlanModel.getId());
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XUNCHA_PLAN_STATUS_URL, INFO_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 获取列表
     */
    private void initQusHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        // 已完成
        StringBuilder stringBuilder = new StringBuilder();
        for (XunChaBuildingModel xunChaBuildingModel:xunChaPlanModel.getBuildingList()){
            for (XunChaFloorModel xunChaFloorModel:xunChaBuildingModel.getChildren()){
                if (StringUtils.isEmpty(stringBuilder.toString())){
                    stringBuilder.append(xunChaFloorModel.getId());
                }else {
                    stringBuilder.append("," + xunChaFloorModel.getId());
                }
            }
        }
        hashMap.put("id", stringBuilder.toString());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XUNCHA_QUESTION_LIST_URL, QUS_LIST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }


    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what) {
                    case INFO_LIST_REQUEST_WHAT:
                        LinkedList<XunChaBuildingModel> xunChaListModels = (LinkedList<XunChaBuildingModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(dataStr), XunChaBuildingModel.class);
                        bundle.putSerializable("list", xunChaListModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case QUS_LIST_WHAT:
                        try {
                            LinkedList<XunChaQuestionModel> xunChaQuestionModels = (LinkedList<XunChaQuestionModel>) JSONUtil.jsonArrayToBeanList(
                                    new JSONArray(dataStr), XunChaQuestionModel.class);
                            bundle.putSerializable("list", xunChaQuestionModels);
                            bundle.putBoolean(REQUEST_OK, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                            bundle.putBoolean(REQUEST_OK, false);
                            bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                        }
                        break;
                }
            }catch (Exception e){}
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            if (msg.what == INFO_LIST_REQUEST_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }else if (msg.what == QUS_LIST_WHAT){
                include_progress_bar.setVisibility(View.GONE);
            }
            return;
        }
        switch (msg.what){
            case INFO_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<XunChaBuildingModel>)bundle.getSerializable("list"));
                break;
            case QUS_LIST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setQusListData((LinkedList<XunChaQuestionModel>)bundle.getSerializable("list"));
                break;
        }
    }

    private void setListData(LinkedList<XunChaBuildingModel> list) {
        if (null == list || list.size() == 0){
            xunChaSelectBuildAdapter.clear();
            return;
        }
        include_no_data.setVisibility(View.GONE);
       // xunChaSelectBuildAdapter.setFloorId(floorId);
        xunChaSelectBuildAdapter.clear();
        xunChaSelectBuildAdapter.addDatas(list);
    }

    private void setQusListData(LinkedList<XunChaQuestionModel> list) {
        xunChaQuestionAdapter.clear();
        if (null == list || list.size() == 0){
            ll_que_title.setVisibility(View.GONE);
            return;
        }
        ll_que_title.setVisibility(View.VISIBLE);
        include_no_data.setVisibility(View.GONE);
        xunChaQuestionAdapter.addDatas(list);
    }

}
